const fs = require('fs')
const path = require('path')

const main = () => {
    const configPath = path.join(__dirname, './PE策略配置.json')
    const configData = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
    const config = configData.config[configData.currentIndex]
    const { strategyName, idList, weightList } = config
    const contextList = []

    contextList.push(`// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sword_snow

//@version=4
strategy('${strategyName}螺丝钉策略估值定投回测', pyramiding=10000)
strategy.risk.allow_entry_in(strategy.direction.long) // 限制只能做多

// 回测时间控制
fromYear = input(defval = 2018, title = '起始年', minval = 2000)
fromMonth = input(defval = 10, title = '起始月', minval = 1, maxval = 12)
fromDay = input(defval = 1, title = '起始日', minval = 1, maxval = 31)

endYear = input(defval = 2021, title = '结束年', minval = 2000)
endMonth = input(defval = 4, title = '结束月', minval = 1, maxval = 12)
endDay = input(defval = 1, title = '结束日', minval = 1, maxval = 31)

startTime = timestamp(fromYear, fromMonth, fromDay, 00, 00) 
endTime = timestamp(endYear, endMonth, endDay, 23, 59) 

isInTimeRange() => time >= startTime and time <= endTime

sumWeight = 0.0
stockCount = 0
weightList = array.new_float(0)
peList = array.new_float(0)
averagePE = 0.0
_EPS = 0.0
_close = 0.0
_PE = 0.0
_weight = 0.0
    `)

    if (idList.length !== weightList.length) {
        throw new Error('id 数量必须和权重数量相同')
    }

    for (let i = 0; i < idList.length; i++) {
        contextList.push(`
// ↓ 复制单元 ------
stockCount += 1
_weight := ${weightList[i]}
_EPS := financial('${idList[i]}', "EARNINGS_PER_SHARE", "TTM")
_close := security('${idList[i]}', "W", close)
_PE := _close / _EPS
array.push(peList, _PE)
array.push(weightList, _weight)
// ↑ --------------
        `)
    }

    contextList.push(`
sumWeight := array.sum(weightList)

for _i = 0 to stockCount - 1
    averagePE += array.get(peList, _i) * (array.get(weightList, _i) / sumWeight)

EP100 = (1 / averagePE) * 100

// 螺丝钉策略 ---------------------
toLong = EP100 > 10
toShort = EP100 < 6.4

if toLong
    strategy.entry('买', true, when = isInTimeRange())

if toShort
    strategy.entry('卖', false, when = isInTimeRange())
// --------

if(time > timestamp(syminfo.timezone, endYear, endMonth, endDay, 23, 59))
    strategy.close_all()

plot(EP100, color=color.new(#db5a6b, 20), linewidth=2)

p1 = plot(10, color=color.new(#0eb83a, 50))
p2 = plot(6.4, color=color.new(#0eb83a, 50))
fill(p1, p2, color=color.new(#0eb83a, 80))

    `)

    fs.writeFileSync(`./${strategyName}螺丝钉策略估值定投回测.pine`, contextList.join('\n'), 'utf8')

}


main()
